package com.xuecheng.framework.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Feign拦截器
 * @author zhaoxiang
 * @version 1.0
 * @Date 2020/2/25 15:21
 */
public class FeignClientInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null){
                HttpServletRequest request = requestAttributes.getRequest();
                //取出当前请求的header，找到jwt令牌
                Enumeration<String> headerNames = request.getHeaderNames();
                if(headerNames != null){
                    while (headerNames.hasMoreElements()){
                        String headerName = headerNames.nextElement();
                        String headerValue = request.getHeader(headerName);
                        // 使用Feign下RequestTemplate的将header向下传递
                        requestTemplate.header(headerName, headerValue);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
